import dayjs from "dayjs";
import * as ExcelJS from "exceljs/dist/exceljs.min.js";
import FileSaver from "file-saver";
import { ElNotification, ElMessage, ElMessageBox } from "element-plus";
import useSeatStore from "@/store/seat.js";

const seatStore = useSeatStore();

export default function () {
  const source = getSource();

  let fileName = "2KT历史扇区数据查询结果@" + dayjs().format("YYYYMMDD_HHmmss");
  const workbook = new ExcelJS.Workbook();
  const worksheet = workbook.addWorksheet("2KT历史扇区数据", {
    views: [{ state: "frozen", xSplit: 1, ySplit: 1 }],
  });

  worksheet.columns = [
    { header: "序号", key: "number", width: 10 },
    { header: "开始时间", key: "startTime", width: 24 },
    { header: "结束时间", key: "endTime", width: 24 },
    { header: "时长(分钟)", key: "minutes", width: 12 },
    { header: "时长(小时)", key: "hours", width: 12 },
    { header: "扇区数", key: "count", width: 10 },
    { header: "运行方向", key: "direction", width: 12 },
    { header: "扇区详情", key: "content", width: 100 },
  ];

  source.forEach((row) => {
    worksheet.addRow(row);
  });

  worksheet.properties.defaultRowHeight = 15;
  worksheet.eachRow(function (row, rowNumber) {
    row.eachCell(function (cell, colNumber) {
      cell.alignment = {
        vertical: "middle",
        horizontal: colNumber < 8 ? "center" : "left",
        wrapText: true,
      };
      if (rowNumber == 1) {
        cell.font = { size: 12, bold: true };
      } else {
        cell.font = { size: 12 };
      }
    });
  });

  workbook.xlsx.writeBuffer().then((buffer) => {
    const fileData = new Blob([buffer], {
      type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8",
    });
    FileSaver.saveAs(fileData, fileName + ".xlsx");
    resolve(fileName);
  });
}

const getSource = () => {
  let source = null;
  if (!seatStore.historyView.queryResult) {
    source = [];
  } else if (!seatStore.historyView.queryConfig.ignoreShort) {
    source = seatStore.historyView.queryResult;
  } else {
    source = seatStore.historyView.queryResult.filter(
      (cell) =>
        !cell.endTime ||
        dayjs(cell.endTime).diff(cell.startTime, "minute") >= 10
    );
  }
  source = JSON.parse(JSON.stringify(source));
  return source.map((cell) => {
    let startDay = dayjs(cell.startTime);
    let endDay = cell.endTime ? dayjs(cell.endTime) : dayjs();
    let minutes = endDay.diff(startDay, "minute");
    let hours = Math.round(endDay.diff(startDay, "hour", true) * 10) / 10;
    let content = "";
    Object.keys(cell.content).forEach((seatCode) => {
      content += seatCode + ": ";
      cell.content[seatCode].forEach((sectorCode) => {
        content += sectorCode + " ";
      });
      content = content.trim();
      content += ";\n";
    });
    content = content.trim();
    cell.content = content;
    cell["minutes"] = minutes;
    cell["hours"] = hours;
    cell.endTime = cell.endTime ? cell.endTime : "未结束";
    return cell;
  });
};
